package dyyx.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;

public abstract class EsDemoUtils {
	
	public static String doCreateIndex(HttpServletRequest req) throws Exception {
        String server = req.getParameter("server");
		if(StringUtils.isBlank(server)){
			return "server is blank";
		}
		server = server.trim();
		
		String indexCreateUrl = server + "/simplearticles";
		
		String indexCreateJson = FileUtil.readStringFromResource("data/index.txt", null);
		
		String indexCreateResult = EsClientUtils.doExecute(indexCreateUrl, "PUT", indexCreateJson, null);
		
		String typeCreateUrl = server + "/simplearticles/_mapping/simplearticle";

		String typeCreateJson = FileUtil.readStringFromResource("data/type.txt", null);

		String typeCreateResult = EsClientUtils.doExecute(typeCreateUrl, "PUT", typeCreateJson, null);

		String str = indexCreateUrl +"\n";
		str = str + indexCreateJson +"\n";
		str = str + indexCreateResult +"\n\n\n";
		
		str = str + "--------- \n";

		str = str + typeCreateUrl +"\n";
		str = str + typeCreateJson +"\n";
		str = str + typeCreateResult +"\n\n\n";
		
		
		return str;
	}

	
	public static String doIndex(HttpServletRequest req) throws Exception {
		String server = req.getParameter("server");
		
		
		if(StringUtils.isBlank(server)){
			return "server is blank";
		}
		server = server.trim();
		
		List<String> lines = FileUtil.readLinesFromResource("data/data.txt", null);
		if(lines==null || lines.isEmpty()){
			return "data lines is empty";
		}
		int num = lines.size();
		String url = server +"/simplearticles/simplearticle" ;
		String result = null;
		for(int i=0;i<num;i++){
			Map<String,Object> map = new HashMap<>();
			String content = lines.get(i);
            int id = i+1;
            int length = content.length();
			map.put("id", id);
			map.put("content", content);
			map.put("length",length);
            String json = JSON.toJSONString(map);
            String indexUrl = url +"/"+id;
			result = EsClientUtils.doExecute(indexUrl, "PUT", json, null);
		}
		
		return "indexDemo done,num="+num+",result="+result;

	}

}